{extend name="common/layoutUser" /}

{block name="body"}
<div class="user-modular-account">
    <div class="user-modular-title">帐户设置</div>
    <div class="layui-tab" lay-filter="tab">
        <ul class="layui-tab-title">
            <li data-tab="base" class="layui-this">基本信息</li>
            <li data-tab="avatar">修改头像</li>
            <li data-tab="account">账号绑定</li>
        </ul>
        <div class="layui-tab-content">
            <!-- 基本信息 -->
            <div class="layui-tab-item layui-show">
                <form class="layui-form information">
                    <div class="layui-form-item">
                        <label for="account" class="layui-form-label">登录账号</label>
                        <div class="layui-input-inline">
                            <input type="text" id="account" value="{$userInfo.account}"
                                   autocomplete="off" readonly class="layui-input layui-disabled">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label for="register" class="layui-form-label">注册时间</label>
                        <div class="layui-input-inline">
                            <input type="text" id="register" value="{$userInfo.create_time}"
                                   autocomplete="off" readonly class="layui-input layui-disabled">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label for="nickname" class="layui-form-label">用户昵称</label>
                        <div class="layui-input-inline">
                            <input type="text" id="nickname" name="nickname" value="{$userInfo.nickname}"
                                   autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户性别</label>
                        <div class="layui-input-block">
                            <input type="radio" name="gender" value="0" title="保密" {if $userInfo.gender==0}checked{/if}>
                            <input type="radio" name="gender" value="1" title="男" {if $userInfo.gender==1}checked{/if}>
                            <input type="radio" name="gender" value="2" title="女" {if $userInfo.gender==2}checked{/if}>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label for="sign" class="layui-form-label">个性签名</label>
                        <div class="layui-input-inline">
                            <textarea id="sign" name="sign" placeholder="这家伙很懒什么都没有留下~" class="layui-textarea">{$userInfo.sign??''}</textarea>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label"></label>
                        <div class="layui-input-inline">
                            <button type="button" class="layui-btn layui-btn-default" lay-filter="updateSubmit" lay-submit>确认修改</button>
                        </div>
                    </div>
                </form>
            </div>
            <!-- 修改头像 -->
            <div class="layui-tab-item">
                <form class="layui-form avatar">
                    <div class="explain"></div>
                    <div class="upload">
                        <div class="wrapper">
                            <input type="hidden" id="avatar" name="avatar" value="{$userInfo.avatar}">
                            <img src="{$userInfo.avatar}" alt="avatar" id="uploadAvatar">
                        </div>
                        <button type="button" class="layui-btn layui-btn-default" lay-filter="saveAvatar" lay-submit>确认修改</button>
                    </div>
                    <div class="clearfix"></div>
                </form>
            </div>
            <!-- 账号绑定 -->
            <div class="layui-tab-item">
                <ul class="binding">
                    <li>
                        <div class="icon">
                            <i class="layui-icon layui-icon-email"></i>
                        </div>
                        <div class="info">
                            <p>
                                <span>邮箱  </span>
                                {if $userInfo.email}
                                <em>{$userInfo.email} 已绑定</em>
                                {else}
                                <em style="color:red;">未绑定</em>
                                {/if}
                            </p>
                            <p>邮箱号用于接收网站重要的信息通知</p>
                        </div>
                        <div class="update">
                            <a class="layui-btn layui-btn-radius layui-bg-gray" lay-event="bindEmail">{$userInfo.email ? '更改' : '绑定'}</a>
                        </div>
                    </li>
                    <li>
                        <div class="icon">
                            <i class="layui-icon layui-icon-cellphone"></i>
                        </div>
                        <div class="info">
                            <p>
                                <span>手机  </span>
                                {if $userInfo.mobile}
                                <em>{$userInfo.mobile} 已绑定</em>
                                {else}
                                <em style="color:red;">未绑定</em>
                                {/if}
                            </p>
                            <p>手机号可用于登录或者密码找回等</p>
                        </div>
                        <div class="update">
                            <a class="layui-btn layui-btn-radius layui-bg-gray" lay-event="bindMobile">{$userInfo.mobile ? '更改' : '绑定'}</a>
                        </div>
                    </li>
                    <li>
                        <div class="icon">
                            <i class="layui-icon layui-icon-vercode"></i>
                        </div>
                        <div class="info">
                            <p>
                                <span>密码  </span>
                                <em>****** 已设置</em>
                            </p>
                            <p>密码很重要请谨慎保管不要泄露</p>
                        </div>
                        <div class="update">
                            <a class="layui-btn layui-btn-radius layui-bg-gray" lay-event="changePwd">更改</a>
                        </div>
                    </li>
                    <li>
                        <div class="icon">
                            <i class="layui-icon layui-icon-login-wechat"></i>
                        </div>
                        <div class="info">
                            <p>
                                <span>微信  </span>
                                {if $userInfo.isWeChat}
                                <em>****** 已绑定</em>
                                {else}
                                <em style="color:red;">未绑定</em>
                                {/if}
                            </p>
                            <p>可使用微信扫码快速登录</p>
                        </div>
                        <div class="update">
                            <a class="layui-btn layui-btn-radius layui-bg-gray" lay-event="bindWeChat">{$userInfo.isWeChat ? '更改' : '绑定'}</a>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>
{/block}

{block name="js"}
<script>
    layui.use(['form', 'upload'], function () {
        let $ = layui.$;
        let form = layui.form;
        let upload = layui.upload;
        let timerWx = null;

        // 监听事件
        waitUtil.event({
            'changePwd': function () {
                waitUtil.popup({
                    title: '修改密码',
                    url: "{:route('user/binding', ['field'=>'changePwd'])}",
                    area: ['320px', '300px'],
                    success: function (layero, index) {
                        layero.layui.form.on('submit(addForm)', function(data) {
                            const that = $(this);
                            waitUtil.locking(that);
                            if (data.field['newPassword'].length < 6 || data.field['newPassword'].length > 18) {
                                waitUtil.unlock(that);
                                return layer.msg('密码必须是6~18个字符内');
                            }

                            if (data.field['newPassword'] !== data.field['okPassword']) {
                                waitUtil.unlock(that);
                                return layer.msg('两次密码输入不一致');
                            }

                            waitUtil.ajax({
                                url: "{:route('user/binding')}",
                                type: 'POST',
                                data: {
                                    field: 'changePwd',
                                    newPassword: data.field['newPassword'],
                                    oldPassword: data.field['oldPassword']
                                }
                            }).then((res) => {
                                waitUtil.unlock(that);
                                if (res.code === 0) {
                                    layer.close(index);
                                }
                            });
                        });
                    }
                });
            },
            'bindWeChat': function () {
                layer.closeAll();
                $.ajax({
                    url: "{:route('user/buildWxUrl')}",
                    dataType: 'html',
                    cache: false,
                    async: false,
                    success: function (res) {
                        layer.open({
                            type: 1,
                            resize: false,
                            scrollbar: false,
                            title: false,
                            skin: 'popup-skin-session',
                            shade: 0.5,
                            area: ['380px'],
                            content: res,
                            success: function(layero) {
                                queryWxCodeUrl(layero)
                            }
                        });
                    }
                });
            },
            'bindMobile': function () {
                waitUtil.popup({
                    title: '绑定手机号',
                    url: "{:route('user/binding', ['field'=>'bindMobile', 'value'=>$userInfo.mobile])}",
                    area: ['370px', '250px'],
                    success: function (layero, index) {
                        layero.layui.form.on('submit(addForm)', function(data){
                            waitUtil.ajax({
                                url: "{:route('user/binding')}",
                                type: 'POST',
                                data: {field: 'bindMobile', mobile: data.field['mobile'], code: data.field['code']}
                            }).then((res) => {
                                if (res.code === 0) {
                                    layer.close(index);
                                }
                            });
                        });
                    }
                });
            },
            'bindEmail': function () {
                waitUtil.popup({
                    title: '绑定邮箱',
                    url: "{:route('user/binding', ['field'=>'bindEmail', 'value'=>$userInfo.email])}",
                    area: ['370px', '250px'],
                    maxmin: false,
                    success: function (layero, index) {
                        layero.layui.form.on('submit(addForm)', function(data){
                            waitUtil.ajax({
                                url: "{:route('user/binding')}" ,
                                type: 'POST',
                                data: {field: 'bindEmail', mobile: data.field['email'], code: data.field['code']}
                            }).then(res => {
                                if (res.code === 0) {
                                    layer.close(index);
                                }
                            });
                        });
                    }
                });
            }
        });

        // 账号更新
        form.on('submit(updateSubmit)', function(data) {
            layer.confirm('您确定要进行更新吗？', function(index) {
                layer.close(index);
                waitUtil.ajax({
                    url: "{:route('user/edit')}",
                    type: 'POST',
                    data: data.field
                });
            });
        });

        // 修改头像
        form.on('submit(saveAvatar)', function(data) {
            const that = $(this)
            waitUtil.locking(that);
            layer.confirm('您确定要进行保存吗？', function(index) {
                layer.close(index);
                waitUtil.ajax({
                    url: "{:route('user/binding')}",
                    type: 'POST',
                    data: {field: 'changeAvatar', avatar: data.field['avatar']}
                }).then(() => {
                    waitUtil.unlock(that);
                }).catch(() => {
                    waitUtil.unlock(that);
                });
            });
        });

        // 上传头像
        upload.render({
            elem: '#uploadAvatar'
            ,url: '{:route("upload/temporary")}'
            ,field: 'file'
            ,accept: 'images'
            ,acceptMime: 'image/*'
            ,exts: 'jpg|png|jpeg'
            ,size: 1024 * 10
            ,data: {type: 'picture'}
            ,done: function (res) {
                if (res.code === 0) {
                    $('#avatar').val(res.data.url);
                    $('#uploadAvatar').attr('src', res.data.url);
                } else {
                    layer.msg(res.msg);
                }
            }
        });

        // 微信二维码
        function queryWxCodeUrl(that) {
            waitUtil.ajax({
                url:  "{:route('user/buildWxUrl')}",
                fulShow: false,
                type: 'POST'
            }).then((res) => {
                const elem = $(that).find('.qrCode img');
                elem.show();
                elem.attr('src', res.data.url);
                ticketBindWx(res.data.key);
                setTimeout(function () {
                    $(that).find('.loading').hide();
                }, 100)
            });
        }

        // 心跳检测绑定
        function ticketBindWx(key) {
            if (!key) {
                stopInterval();
                return;
            }
            timerWx = setInterval(function () {
                const el = '.user-modular-bindWx .masking';
                if ($(el).length <= 0) {
                    stopInterval();
                    return;
                }
                waitUtil.ajax({
                    url: "{:route('user/ticketBindWx')}?key="+key,
                    fulShow: false,
                    type: 'GET'
                }).then((res) => {
                    if (res.code !== 0) {
                        stopInterval();
                        layer.msg(res.msg);
                    } else if (res.data.status === undefined || res.data.status === 2) {
                        stopInterval();
                        const el = '.user-modular-bindWx .masking';
                        $(el).show();
                        layer.msg(res.data.error);
                    } else if (res.data.status === 1) {
                        stopInterval();
                        layer.msg(res.data.error);
                        setTimeout(function () {
                            location.reload();
                        }, 1000);
                    }
                });
            }, 1500)
        }

        // 停止心跳检测
        function stopInterval() {
            if (timerWx !== null) {
                clearInterval(timerWx);
                timerWx = null;
            }
        }
    });
</script>
{/block}
